<template>
  <div ref="dashboardChart" style="width: 400px; height: 400px;"></div>
</template>

<script setup>
import { ref, watch, onMounted, onBeforeUnmount } from 'vue';
import * as echarts from 'echarts';

const props = defineProps({
  Capacity: {
    type: [Number, String],
    default: 0,
    validator: (value) => {
      return typeof value === 'number' || (typeof value === 'string' && /^[0-9]+(\.[0-9]+)?$/.test(value));
    }
  }
});

const dashboardChart = ref(null);
let chartInstance = null;

const initChart = () => {
  if (!dashboardChart.value) return;
  chartInstance = echarts.init(dashboardChart.value);
  let capacityValue = Number(props.Capacity);
  capacityValue /= 2; // 假设是百分比，转换为0-1
  const option = {
    tooltip: {
      formatter: '{a} <br/>{b} : {c}%'
    },
    series: [
      {
        type: 'gauge',
        detail: {
          formatter: '{value}%'
        },
        axisLine: {
          lineStyle: {
            color: [[0.6, '#1eff00'], [0.8,'#f1e700'],[1, '#ff4500']],
            width: 10
          }
        },
        data: [{
          value: capacityValue,
          name: '装载量'
        }]
      }
    ]
  };
  chartInstance.setOption(option);
};

watch(() => props.Capacity, (newValue) => {
  if (chartInstance) {
    let capacityValue = Number(newValue);
    if (capacityValue > 1) {
      capacityValue /= 2;
    }
    chartInstance.setOption({
      series: [{
        data: [{
          value: capacityValue,
          name: '装载量'
        }]
      }]
    });
  }
});

onMounted(() => {
  initChart();
});

onBeforeUnmount(() => {
  if (chartInstance) {
    chartInstance.dispose();
  }
});
</script>

<style scoped>
</style>
